<?php

App::uses('HtmlHelper', 'View/Helper');
App::uses('Inflector', 'Utility');
App::import('Model', 'Usuarios.Permissao');

class BoostCakeHtmlHelper extends HtmlHelper {

    public $helpers = array('Html', 'Session');
    private $__acoes = array();

    /**
     * Overwrite HtmlHelper::useTag()
     * If $tag is `<input type="radio">` then replace `<label>` position
     * Returns a formatted existent block of $tags
     *
     * @param string $tag Tag name
     * @return string Formatted block
     */
    public function useTag($tag) {
        $args = func_get_args();

        if ($tag === 'radio') {
            $class = (isset($args[3]['class'])) ? $args[3]['class'] : 'radio';
            unset($args[3]['class']);
        }

        $html = call_user_func_array(array('parent', 'useTag'), $args);

        if ($tag === 'radio') {
            $regex = '/(<label)(.*?>)/';
            if (preg_match($regex, $html, $match)) {
                $html = $match[1] . ' class="' . $class . '"' . $match[2] . preg_replace($regex, ' ', $html);
            }
        }

        return $html;
    }

    /**
     * Creates a formatted IMG element.
     *
     * This method will set an empty alt attribute if one is not supplied.
     *
     * ### Usage:
     *
     * Create a regular image:
     *
     * `echo $this->Html->image('cake_icon.png', array('alt' => 'CakePHP'));`
     *
     * Create an image link:
     *
     * `echo $this->Html->image('cake_icon.png', array('alt' => 'CakePHP', 'url' => 'http://cakephp.org'));`
     *
     * ### Options:
     *
     * - `url` If provided an image link will be generated and the link will point at
     *   `$options['url']`.
     * - `fullBase` If true the src attribute will get a full address for the image file.
     * - `plugin` False value will prevent parsing path as a plugin
     * - `data-src` For holder.js options. If `$path` is not empty, then unset `$options['data-src']`.
     *
     * @param string $path Path to the image file, relative to the app/webroot/img/ directory.
     * @param array $options Array of HTML attributes. See above for special options.
     * @return string completed img tag
     * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::image
     */
    public function image($path, $options = array()) {
        if (empty($path)) {
            $path = '/';
        } else {
            if (isset($options['data-src'])) {
                unset($options['data-src']);
            }
        }
        return parent::image($path, $options);
    }

    public function setAcoes($title, $url = NULL, $options = array(), $confirmMessage = false) {
        $matches = null;
        $returnValue = preg_match('#<i[^>]*>.*?</i>#si', $title, $matches);
        if ($returnValue > 0) {
            $new_title = trim(strip_tags(str_replace(array($matches[0], '&nbsp;'), '', $title)));
            $title = $matches[0] . '<span class="acoes_titulo"> ' . $new_title . '</span>';
        }
        if ($url == NULL) {
            $this->__acoes[] = $title;
        } else {
            $retorno = self::link($title, $url, $options, $confirmMessage);
            //$retorno = self::linkPermissao($title, $url, $options, $confirmMessage);
            //if ($retorno != '') {
            $this->__acoes[] = $retorno;
            //}
        }
    }

    public function getAcoes() {
        if (count($this->__acoes) > 0) {
            $retorno = "<ul>";
            foreach ($this->__acoes as $key => $value) {
                $retorno .= '<li style="display: inline-block;margin:10px 3px 0px 3px;">' . $value . "</li>";
            }
            $retorno .= "</ul>";
            return $retorno;
        }
        return NULL;
    }

    public function link($title = '', $url = null, $options = array(), $confirmMessage = false) {
        if (isset($options['icon'])) {
            $options['escape'] = FALSE;
            $title = '<i class="' . $options['icon'] . '"> ' . $title . '</i>';
        }
        if (!isset($options['title'])) {
            if (is_array($url) AND isset($url['action'])) {
                $options['title'] = __(Inflector::camelize($url['action']));
            }
        }
        return parent::link($title, $url, $options, $confirmMessage);
    }

    public function linkPermissao($title, $url = null, $options = array(), $confirmMessage = false) {
        if (count($this->__permissao($url)) > 0) {
            return self::link($title, $url, $options, $confirmMessage);
        }
        return '';
    }

    private function __permissao($url = null) {
        $new_url = array(
            'plugin' => '',
            'controller' => '',
            'action' => 'index',
        );
        $url = str_replace($this->request->base, '', $this->Html->url($url));
        $_url = explode('/', ltrim(rtrim(str_replace($this->request->params['prefix'], '', $url), '/'), '/'));
        if (count($_url) > 2) {
            list($plugin, $controller, $action) = $_url;
            $plugin = Inflector::camelize($plugin);
            if (CakePlugin::loaded($plugin)) {
                $new_url['plugin'] = Inflector::underscore($plugin);
                $new_url['controller'] = Inflector::underscore($controller);
                $new_url['action'] = $action;
            } else {
                $new_url['plugin'] = '';
                $new_url['controller'] = Inflector::underscore($plugin);
                $new_url['action'] = $controller;
            }
        } else {
            if (count($_url) == 1) {
                list($plugin) = $_url;
                $controller = $plugin;
            } else {
                list($plugin, $controller) = $_url;
            }
            $plugin = Inflector::camelize($plugin);
            if (CakePlugin::loaded($plugin)) {
                $new_url['plugin'] = Inflector::underscore($plugin);
                $new_url['controller'] = Inflector::underscore($controller);
                $new_url['action'] = 'index';
            } else {
                $new_url['plugin'] = '';
                $new_url['controller'] = Inflector::underscore($plugin);
                $new_url['action'] = 'index';
            }
        }
        $model = new Permissao();
        $users = $this->Session->read('Auth.User.id');
        $b_consulta = $model->query('SELECT 
                                        Menu.*
                                     FROM
                                        usuarios AS Usuario
                                            INNER JOIN
                                        permissoes AS Permissao ON Usuario.id = Permissao.usuario_id
                                            INNER JOIN
                                        menus AS Menu ON Menu.id = Permissao.menu_id
                                     WHERE
                                        Usuario.id = ' . (int) $users . ' AND Usuario.status = 1 AND prefixo="' . $this->request->params['prefix'] . '" AND Menu.controller = "' . $new_url['controller'] . '" AND Menu.action = "' . $new_url['action'] . '" AND Menu.plugin = "' . $new_url['plugin'] . '"');

        unset($users);
        return $b_consulta;
    }

    public function permissao($url = null) {
        if (count($this->__permissao($url)) > 0) {
            return TRUE;
        }
        return FALSE;
    }

    public function status($id) {
        $retorno = array(
            0 => array('class' => 'warning', 'text' => __('Inativo')),
            1 => array('class' => 'success', 'text' => __('Ativo')),
            9 => array('class' => 'danger', 'text' => __('Excluido')),
        );
        return '<span class="label label-' . $retorno[$id]['class'] . '">' . $retorno[$id]['text'] . '</span>';
    }

    public function simNao($id) {
        $retorno = array(
            0 => array('class' => 'warning', 'text' => 'Não'),
            1 => array('class' => 'success', 'text' => 'Sim'),
        );
        return '<span class="label label-' . $retorno[$id]['class'] . '">' . $retorno[$id]['text'] . '</span>';
    }

    public function encode($string) {
        $tmp = base64_encode($string);
        return str_replace(array('/', '='), array('-', '_'), $tmp);
    }

    public function urlTitle($str, $separator = '-', $lowercase = FALSE) {
        if ($separator === 'dash') {
            $separator = '-';
        } elseif ($separator === 'underscore') {
            $separator = '_';
        }

        $array1 = array("á", "à", "â", "ã", "ä", "é", "è", "ê", "ë", "í", "ì", "î", "ï", "ó", "ò", "ô", "õ", "ö", "ú", "ù", "û", "ü", "ç"
            , "Á", "À", "Â", "Ã", "Ä", "É", "È", "Ê", "Ë", "Í", "Ì", "Î", "Ï", "Ó", "Ò", "Ô", "Õ", "Ö", "Ú", "Ù", "Û", "Ü", "Ç");
        $array2 = array("a", "a", "a", "a", "a", "e", "e", "e", "e", "i", "i", "i", "i", "o", "o", "o", "o", "o", "u", "u", "u", "u", "c"
            , "A", "A", "A", "A", "A", "E", "E", "E", "E", "I", "I", "I", "I", "O", "O", "O", "O", "O", "U", "U", "U", "U", "C");

        $str = str_replace($array1, $array2, $str);

        $q_separator = preg_quote($separator, '#');

        $trans = array(
            '&.+?;' => '',
            '[^a-z0-9 _-]' => '',
            '\s+' => $separator,
            '(' . $q_separator . ')+' => $separator
        );

        $str = strip_tags($str);
        foreach ($trans as $key => $val) {
            $str = preg_replace('#' . $key . '#i', $val, $str);
        }

        if ($lowercase === TRUE) {
            $str = strtolower($str);
        }

        return trim(trim($str, $separator));
    }

}
